<?php

namespace app\common\model\Member;

use app\common\model\Base;
use think\facade\Config;
use think\Db;

class Member extends Base
{
    protected $name = 'member';

    //性别 0：其他、1：男、2：女
    public $sexs = [
//        0=>'其他',
        1 => '男',
        2 => '女'
    ];

    public $types = [ //用户类型
        0 => '外部用户',
        1 => '内部用户',
        2 => '种子用户',
    ];

    const PARTNER = 1; //合伙人
    public $identitys = [ //这里以后可以添加不同的身份
        0 => '',
        1 => '合伙人',
    ];

    public function file()
    {
        return $this->hasMany('app\common\model\member\File', 'member_id');
    }


    public function getMemberList($condition = [], $field = '*', $order = 'm1.id asc', $page = -1)
    {
        if ($page == -1) {
            $page = Config::get('paginate.list_rows');
        }
        $res = $this->alias('m1')
            ->where($condition)
            ->join('member m2', 'm1.parent_id=m2.id', 'left')
            ->join('area a', 'a.id=m1.city', 'left')
            ->join('member_level m_l', 'm_l.level=m1.level')
            ->field($field)
            ->order($order);

        if ($page == 0) {
            $res = $res->select()->toArray();
//            foreach ($res as &$item) {
//                if ($item['province'] > 0 && $item['city'] > 0) {
//                    if (isset($area[$item['province']][$item['city']])) {
//                        $item['city'] = $area[$item['province']][$item['city']];
//                    } else if (isset($area[$item['province']]) && count($area[$item['province']])) {
//                        $item['city'] = $area[$item['province']];
//                    }
//                }
//            }
            return $res;
        } else {
//            $res = $res->paginate($page, false, ['query' => request()->param()])->each(function ($item, $key) use ($area) {
//                if ($item['province'] > 0 && $item['city'] > 0) {
//                    if (isset($area[$item['province']][$item['city']])) {
//                        $item['city'] = $area[$item['province']][$item['city']];
//                    } else if (isset($area[$item['province']]) && count($area[$item['province']])) {
//                        $item['city'] = $area[$item['province']];
//                    }
//                }
//                return $item;
//            });
            $res = $res->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $res;
            return $res->items();
        }
    }


    /**
     * User:Simony
     * Function:创建邀请码
     * @return string
     */
    public function createInviteCode()
    {
        $code = strtoupper(randStr(6, 2));
        $count = $this->getCount(['invite_code' => $code]);
        if ($count > 0) {
            return $this->createInviteCode();
        }
        return $code;
    }

    /**
     * User:Simony
     * Function: 根据出生日期计算年龄、生肖、星座
     * @param string $mydate = "2018-10-23" 日期
     * @param string $symbol 符号
     * @return mixed
     */
    function birthday($mydate, $symbol = '-')
    {

        //计算年龄
        $birth = $mydate;
        list($by, $bm, $bd) = explode($symbol, $birth);
        $cm = date('n');
        $cd = date('j');
        $age = date('Y') - $by - 1;
        if ($cm > $bm || $cm == $bm && $cd > $bd) $age++;
        $array['age'] = $age > 0 ? $age : 0;

        //计算生肖
        $animals = array(
            '鼠', '牛', '虎', '兔', '龙', '蛇',
            '马', '羊', '猴', '鸡', '狗', '猪'
        );
        $key = ($by - 1900) % 12;
        $array['animals'] = $animals[$key];

        //计算星座
        $constellation_name = [
            '水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座',
            '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座'
        ];

        if ($bd <= 22) {
            $constellation = '1' != $bm?$constellation_name[$bm - 2]:$constellation_name[11];
        } else {
            $constellation = $constellation_name[$bm - 1];
        }
        $array['constellation'] = $constellation;

        return $array;
    }


    /**
     * User:Simony
     * Function:通过类型获取
     * @param $current_member_id
     * @param $where
     * @param $page
     * @param string $field
     * @param string $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMemberListByType($current_member_id, $where, $page, $field = '*', $order = 'distance asc')
    {

        $where[] = ['m.is_company', 'eq', 0];
        $where[] = ['m.status', 'eq', 1];

        //member_follow_blacklist这个表会全表扫描注意一下后期修改
        $member_sql = $this->field('long_lat_geometry')->where('id', 'eq', $current_member_id)->buildSql();
        $member2_sql = $this->field('geohash')->where('id', 'eq', $current_member_id)->buildSql();

        //拿data
        $join_sql1 = model('common/member/Token')
            ->field("max(`generation_time`) as `generation_time`,member_id")->group("member_id")->buildSql();

        $join_sql2 = model('common/member/FollowBlacklist')->where(['member_id' => $current_member_id])->buildSql();


        $field = Db::raw("DISTINCT {$field},a.name as city,if(m_f_b.type=1,1,0) as is_follow,floor(ST_DISTANCE_SPHERE (({$member_sql}),long_lat_geometry)) distance,astext (long_lat_geometry) point");
        $where1 = 'm.id<>' . $current_member_id;
        $where2 = Db::raw("geohash LIKE concat(LEFT (({$member2_sql}),1),'%')");
        $where3 = Db::raw("ST_DISTANCE_SPHERE (({$member_sql}),long_lat_geometry)");


        $res = $this->alias('m')
            ->field($field)
            ->with(['file' => function ($q) {
                $q->field('id,url,member_id,type')->where(['type' => [1, 2, 3], 'status' => 1]); //文件类型 1：照片、2：阅后即焚、3：红包照片
            }])
            ->join('area a', 'a.id=m.city', 'left')
            ->join($join_sql1 . ' m_t', 'm_t.member_id=m.id', 'left')
            ->join($join_sql2 . ' m_f_b', 'm_f_b.been_member_id=m.id', 'left')
//            ->where([['m_f_b.type','neq',2]]) //排除拉黑
            ->where($where1)
            ->where($where2)
            ->where($where3)
            ->where($where)
            ->where('m_f_b.type = 1 OR m_f_b.type IS NULL')
            ->group('m.id');
        $res = $res->order($order);
        if ($page) {
            $res = $res->paginate($page, false, ['query' => request()->param()])->each(function ($item, $key) {
                $birthday = $this->birthday($item['birthday']);
                $item['age_constellation'] = $birthday['age'] . '岁·' . $birthday['constellation'];
            });

            $this->page_info = $res;
            $res = $res->toArray();
            return $res['data'];
        } else {
            return $res->select()->toArray();
        }
    }


    /**
     * User:Simony
     * Function:获取用户
     * @param $member_id
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMemberInfo($member_id, $field = '*')
    {
        $where['m.id'] = $member_id;
        $res = $this->alias('m')
            ->field($field)
            ->join('area a', 'a.id=m.city', 'left')
            ->where($where)->find();

        return $res ? $res->toArray() : [];
    }

    /**
     * User: Simony
     * Function:关注列表
     * @param $memberId
     * @param $page
     * @param string $field
     * @param string $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function followList($memberId, $page, $field = 'm.*', $order = 'create_time asc')
    {
        $member = $this->getInfoByID($memberId);
        $latitude = $member['latitude'];
        $longitude = $member['longitude'];

        $distance = Db::Raw(" ROUND(
                                            6378.138 * 2 * ASIN(
                                                SQRT(
                                                    POW(
                                                        SIN(
                                                            (
                                                               {$latitude} * PI() / 180 - m.latitude * PI() / 180
                                                            ) / 2
                                                        ),
                                                        2
                                                    ) + COS( {$latitude} * PI() / 180) * COS(m.latitude * PI() / 180) * POW(
                                                        SIN(
                                                            (
                                                                 {$longitude} * PI() / 180 - m.longitude * PI() / 180
                                                            ) / 2
                                                        ),
                                                        2
                                                    )
                                                )
                                            ) * 1000
                                        ) AS distance");

        $field .= ",{$distance},a.name as city";
        $join_sql = model('common/member/Token')->field("max(`generation_time`) as `generation_time`,member_id")->group("member_id")->buildSql();
        $res = $this->alias('m')
            ->field($field)
            ->with(['file' => function ($q) {
                $q->field('id,url,member_id,type')->where(['type' => [1, 2, 3], 'status' => 1]); //文件类型 1：照片、2：阅后即焚、3：红包照片
            }])
            ->join('member_follow_blacklist m_f_b', 'm_f_b.been_member_id = m.id')
            ->join($join_sql . ' m_t', 'm_t.member_id=m.id', 'left')
            ->join('area a', 'a.id=m.city', 'left')
            ->where(['m_f_b.member_id' => $memberId,'m_f_b.type'=>1])
            ->order('distance asc');
        if ($page) {
            $res = $res->paginate($page, false, ['query' => request()->param()])->each(function ($item, $key) {
                $birthday = $this->birthday($item['birthday']);
                $item['age_constellation'] = $birthday['age'] . '岁·' . $birthday['constellation'];
            });

            $this->page_info = $res;
            $res = $res->toArray();
            return $res['data'];
        } else {
            return $res->select()->toArray();
        }
    }


}
